<script setup lang="ts">
import { ref, watch, watchEffect } from "vue";

import { isEmpty } from "lodash";

interface Props {
  options?: (string | undefined)[][];

  optionsDict?: Record<string, string>;

  modelValue?: string[];
}

const props = withDefaults(defineProps<Props>(), {
  options: () => [],
});

interface Emits {
  (event: "update:modelValue", []: (string | undefined)[]): void;
}

const emit = defineEmits<Emits>();

// 选择框
// const value = computed<any>({
//     get() {
//         return props.modelValue;
//     },
//     set(val) {
//         emit('update:modelValue', val);
//     },
// });

// const filteredOptions = computed(() =>
//     [...new Set(props.options.flat())].filter(o => !value.value.includes(o)),
// );

const _options = ref<(string | undefined)[][]>([]);

const value = ref<string[]>([]);

watchEffect(() => {});

watch(
  () => props.options,
  (val) => {
    if (isEmpty(val)) return;
    value.value = [];
    _options.value = [
      [
        ...new Set(
          val.map((option) => {
            return option[0];
          })
        ),
      ].filter(Boolean),
    ];
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  value,
  (val) => {
    console.log(val);
    emit("update:modelValue", val.filter(Boolean));
  },
  {
    deep: true,
  }
);

function handleSelectChange(index: number, val: string, _: Record<string, any>) {
  if (!val || index + 1 < value.value.length) {
    value.value.splice(index + 1);
    _options.value.splice(index + 1);
  }
  const next = props.options.filter((o) => {
    return value.value.every((e) => o?.includes(e));
  });
  if (!isEmpty(next.map((e) => e[value.value.length]).filter(Boolean))) {
    _options.value[index + 1] = [...new Set(next.map((e) => e[value.value.length]))];
  }
}
</script>

<template>
  <!-- <a-select
        class="min-w-64"
        v-model:value="value"
        allowClear
        mode="multiple"
        placeholder="请选择"
        :options="filteredOptions.map(item => ({ value: item }))"
    ></a-select> -->
  <template v-for="(option, index) in _options" :key="index">
    <a-select
      class="w-48"
      v-model:value="value[index]"
      allowClear
      placeholder="请选择"
      style="width: 250px"
      @change="
                (value: string, option: Record<string, any>) =>
                    handleSelectChange(index, value, option)
            "
    >
      <template v-for="item in option">
        <a-select-option :value="item">
          <div class="flex flex-col">
            <span>{{ item }}</span>
            <span>
              {{ optionsDict && item && optionsDict[item] }}
            </span>
          </div>
        </a-select-option>
      </template>
    </a-select>
  </template>
</template>

<style lang="scss" scoped></style>
